package com.rentapark.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import data.DB;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class NotificationHandler  extends Activity{
	public static Context mContext;
	final Context context = this;
	private Button button;
	DB parking_db;
	boolean confirm;
	final NotificationHandler thisActivity = this;
	
	//handles server's response
	private final Handler handler = new Handler() {  
		public void handleMessage(Message msg) { 
			Log.d("buyerConfirmation","confirmed");
			String bundleResult = msg.getData().getString("RESPONSE"); 
			finish();
			
		} 
	}; 
 
	public void onCreate(Bundle savedInstanceState) {
 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gcm_notification);
		//getting db instance
		parking_db=DB.getInstance();
		//button for showing new notification
		button = (Button) findViewById(R.id.buttonShowCustomDialog);
 
		// add button listener
		button.setOnClickListener(new OnClickListener() {
 
		  @Override
		  public void onClick(View arg0) {
 
			// custom dialog
			final Dialog dialog = new Dialog(context);
			dialog.setContentView(R.layout.custom);
			dialog.setTitle("Notification");
			
			if(parking_db.notification_type==0)//this notification informs the spot's owner that he got a request
			{
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("A user has requested your parking spot");

	 
				Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
				// if button is clicked, close the custom dialog
				dialogButton.setText("View request");
				//button for the user to see new requests
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						Log.d("notification","View request");
						Intent intent = new Intent(thisActivity, OwnerList.class);
						
						startActivity(intent);
					}
				});
				//second button not needed in this case
				Button dialogButton2 = (Button) dialog.findViewById(R.id.dialogButtonNo);
				dialogButton2.setVisibility(Button.GONE);
				
			}
			else if(parking_db.notification_type==1)//this notification informs the buyer that th spot's owner confirmed his request
			{
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Your request was accepted by the parking spot's owner");
				Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
				// if button is clicked, close the custom dialog
				parking_db.buyer=true;//this user is the buyer now
				dialogButton.setText("Accept deal");
				//button for the buyer user to accept the deal- finish the 3-way handshake
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						Log.d("notification","deal accepted");
						confirm=true;
						performConfirmPositive();
						//send http post to server including user id, spot id- buyer-confirmation-positive
					}
				});
				//button for the buyer to reject the deal
				Button dialogButton2 = (Button) dialog.findViewById(R.id.dialogButtonNo);
				// if button is clicked, close the custom dialog
				dialogButton2.setText("Reject deal");
				dialogButton2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						Log.d("notification","deal rejected");
						confirm=false;
						performConfirmPositive();
						//send http post to server including user id, spot id- buyer-confirmation-negative
					}
				});
				
			}
			else if(parking_db.notification_type==2)//this notification notifies both buyer and owner that the deal has been confirme
			{
				SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
				SharedPreferences.Editor ed = ref.edit();
				ed.putString("notificationHandler", "finish");
				ed.commit();//this is in order to close the activity afterwards if the activity is onRestart
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Deal Confirmed");
				TextView text2 = (TextView) dialog.findViewById(R.id.text2);
				text2.setText("User's phone number is "+parking_db.userDealPhone);
				Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
				// if button is clicked, close the custom dialog
				dialogButton.setText("Send SMS");
				//this button is for the user to send an sms to the other user
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						try{
						Intent sendIntent = new Intent(Intent.ACTION_VIEW);
						sendIntent.setType("vnd.android-dir/mms-sms");
						sendIntent.putExtra("address", parking_db.userDealPhone);


						startActivity(sendIntent);
						}
						catch (Exception e) {
							Toast.makeText(getApplicationContext(),
								"SMS faild, please try again later!",
								Toast.LENGTH_LONG).show();
							e.printStackTrace();
						}
						
	
					}
				});
				//this button is for the buyer user to go to the map
				Button dialogButton2 = (Button) dialog.findViewById(R.id.dialogButtonNo);
				if(parking_db.buyer==true)
				{
					// if button is clicked, close the custom dialog
				dialogButton2.setText("Go to Map");
				dialogButton2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						Log.d("notification","go to map");
						parking_db.dealClosed=true;
						Intent intent = new Intent(thisActivity, SearchScreen.class);
						startActivity(intent);
						//send http post to server including user id, spot id- buyer-confirmation-negative
					}
				});
				}
				else//if it is the owner, he does not need the map
					dialogButton2.setVisibility(Button.GONE);
				
				
				
			}
			/*
			 * //this notification informs the spot's owner that the deal confirmation hasn't been
			 * complited: the candidate rejected the deal
			 */
			else if(parking_db.notification_type==3)
			{
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("The user who's request was accepted rejected the deal");
				Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
				// if button is clicked, close the custom dialog
				dialogButton.setText("See other requests");
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						Log.d("notification","View request");
						Intent intent = new Intent(thisActivity, OwnerList.class);
						
						startActivity(intent);
					}
				});
				Button dialogButton2 = (Button) dialog.findViewById(R.id.dialogButtonNo);
				dialogButton2.setVisibility(Button.GONE);
			}
 
			
 
			dialog.show();
		  }
		});
	}
	//on Restart-> the activity is automcatically closed
	public void onRestart()
	{
		super.onRestart();
		Log.d("notificationHandler","onRestart");
		SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
		if((ref.getString("notificationHandler", "-1").equals("finish")))
		{
			finish();
		}
	}
	//this method is for sending the server an http post message: buyer confirms the deal
	private void performConfirmPositive() { 
		// create HTTP response handler to handle the HTTP response
		// the response data is extracted from the HTTP message and then it is wrapped in a message
		// which  is passed to the android handler for handling
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    
				//StatusLine status = response.getStatusLine();        
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = data.CommonUtilities.inputStreamToString(entity.getContent());

					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);  
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 


		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				Log.d("dbURL",parking_db.instanceDNS);
				String url="http://";
				url+=parking_db.instanceDNS;
				url+=":8080/ParkAndLetPark/BuyerConfirm";
				Log.d("url is",url);
				HttpPost httppost = new HttpPost(url);
				try {
					try{
						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Response = doc.createElement("MSG_TYPE");
						Response.appendChild(doc.createTextNode("BUYER_CONFIRM"));
						doc.appendChild(Response);
						
						Element type = doc.createElement("CONFIRMATION");
						if(confirm==true)//if buyer accepted the deal- confirmaiton is positive
							type.appendChild(doc.createTextNode("POSITIVE"));
						else//if buyer accepted the deal- confirmaiton is negative
							type.appendChild(doc.createTextNode("NEGATIVE"));
						Response.appendChild(type);


						Element User = doc.createElement("user_id");
						User.appendChild(doc.createTextNode(Double.toString(parking_db.userID)));
						type.appendChild(User);
						
						Element owner = doc.createElement("owner_id");
						owner.appendChild(doc.createTextNode(Double.toString(parking_db.userDealId)));
						Response.appendChild(owner);

						Element ParkingSpot = doc.createElement("ParkingSpot");
						ParkingSpot.appendChild(doc.createTextNode(Integer.toString(parking_db.spotRentId)));
						owner.appendChild(ParkingSpot);

						

						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString","^^^^^^^^^^^^^^^^^^^^"+xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);
						Log.d("work","post executed");


						String response = httpclient.execute(httppost,responseHandler);
						Log.d(""," "+response);

					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (TransformerConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}




				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}

		}.start(); 
	}

}
